package snapex.user.service.impl;

import java.sql.Timestamp;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import snapex.core.SnapexApplicationException;
import snapex.core.mapper.EmployeeInfoMapper;
import snapex.core.model.Employee;
import snapex.core.model.EmployeeInfo;
import snapex.core.model.User;
import snapex.user.service.IEmployeeInfoService;

@Service
public class EmployeeInfoService implements IEmployeeInfoService {
	@Autowired
	private EmployeeInfoMapper employeeInfoMapper;
	
	@Override
	public String createHash(User user) throws SnapexApplicationException {

		EmployeeInfo employee = employeeInfoMapper.selectByPrimaryKey(user.getUsername());
		if (employee != null) {			
			return employee.getHashKey();
		}

		employee = new EmployeeInfo();

		employee.setStaffId(user.getUsername());
		employee.setEmailAddress(user.getEmailAddress());
		
		String hashKey = DigestUtils.md5DigestAsHex(employee.getStaffId().getBytes());

		employee.setHashKey(hashKey);
		
		employee.setCreateTimestamp(new Timestamp(System.currentTimeMillis()));

		if(user instanceof Employee) {
			Employee e = (Employee)user;
			employee.setDepartment(e.getDepartment());
			employee.setDepartmentId(e.getDepartmentId());
			if(e.getExtensionNumber() != null) {
				if(e.getExtensionNumber().length() > 10) {
					employee.setExtensionNo(e.getExtensionNumber().substring(0,10));	
				}else {
					employee.setExtensionNo(e.getExtensionNumber());
				}
			}			
			employee.setManagerId(e.getManagerId());
			employee.setManagerName(e.getManagerName());
			employee.setStaffName(e.getFirstName());
		}
		
		employeeInfoMapper.insert(employee);

		return hashKey;
	}
}
